package x7.heatctrl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

/**
 * checks the weather using the openweathermap.org.
 * 
 *
 */
public class WeatherChecker {

	private String city;
	private JSONObject current;
	
	/**
	 * creates a WeatherChecker
	 * @param city
	 */
	public WeatherChecker(String city) {
		this.city=city;
	}
	
	/**
	 * connects to the openwaethermap and updates the values.
	 * @return true if the current Temperature has changed.
	 */
	public boolean update() {
		try {
			double lastTemp = current==null?Double.MIN_VALUE:getCurrentTemperature();
			double lastPressure = current==null?Double.MIN_VALUE:getCurrentPressure();
			
			JSONObject result = (JSONObject)  JSONValue.parse(
					new URL("http://openweathermap.org/data/2.2/find/name?q="+city+"&cnt=1&lang=de").openStream());
			JSONArray list = (JSONArray) result.get("list");
			if (list.size()>0) 
				current=(JSONObject)list.get(0);
			else
				throw new RuntimeException("Could not find any data for city "+city);
			
			return !equals(lastTemp,getCurrentTemperature()) || !equals(lastPressure,getCurrentPressure());
		} catch (Exception e) {
			Errors.log("Error trying to update the weatherdata from openweathermap.org with city="+city, e);
			return false;
		}
	}

	// returns the value from the current
	private Number getMainNumber(String id) {
		if (current==null) throw new IllegalStateException("no data found");
		return (Number)((JSONObject) current.get("main")).get(id);
	}
	
	//helper for equals with tiny difference
	private static boolean equals(double a, double b) { 		return Math.abs(a-b)<0.001;   	}
	
	/** returns the current temperature in Celsius */
	public double getCurrentTemperature() {	return getMainNumber("temp").doubleValue()- 273.15 ;	}
	
	/** returns the current pressure in bar */
	public double getCurrentPressure() {	return getMainNumber("pressure").doubleValue();  	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		WeatherChecker check =  new WeatherChecker("Timmens");
		check.update();
		System.out.println(check.getCurrentTemperature());
		System.out.println(check.getCurrentPressure());
	}

}
